from flask import Flask, Blueprint, request, redirect, url_for, flash, current_app, render_template, send_from_directory, session
from datetime import datetime
import os
from app.config import create_db_connection
from app.config import compress_and_save_image

list_product_bp = Blueprint('list_product', __name__)

@list_product_bp.before_request
def check_login():
    # 排除登录和静态资源请求
    if request.path == '/login' or request.path.startswith('/static'):
        return

    # 检查用户是否已登录
    if 'username' not in session:
        return redirect('/login')  # 重定向到登录页面
    #如果用户没登录的话，真的返回登录页面


@list_product_bp.route('/product_list')
def product_list():
    keyword = request.args.get('search', None)
    conn, cursor = create_db_connection()
    if keyword:
        query = "SELECT * FROM product_list WHERE product_name LIKE %s OR product_model LIKE %s"
        cursor.execute(query, ('%' + keyword + '%', '%' + keyword + '%'))
    else:
        cursor.execute("SELECT * FROM product_list")
    rows = cursor.fetchall()
    cursor.close()
    conn.close()
    return render_template('product/product_list.html', rows=rows)


@list_product_bp.route('/data/<path:filename>')
def customer_static(filename):
    # 产品列表的产品图片显示模块
    return send_from_directory('../static/data', filename)


@list_product_bp.route('/product_delete/<int:prod_id>', methods=['POST'])
def delete_prod(prod_id):
    conn, cursor = create_db_connection()
    # 根据客户ID执行删除操作
    cursor.execute("DELETE FROM product_list WHERE id = %s", (prod_id,))
    conn.commit()
    cursor.close()
    conn.close()
    # 返回客户列表页面
    flash('删除产品成功!')
    return redirect('/product_list')


@list_product_bp.route('/product_info/<int:prod_id>', methods=['GET'])
def edit_prod(prod_id):
    conn, cursor = create_db_connection()

    # 查询数据库获取产品信息
    cursor.execute("SELECT * FROM product_list WHERE id = %s", (prod_id,))
    product_info = cursor.fetchone()

    if product_info is None:
        cursor.close()
        conn.close()
        return "产品错误,无信息."  # 后续可以添加400页面.

    original_path = product_info[9]
    converted_path = "/" + original_path.replace("\\", "/")

    customer_id = product_info[1]
    class_id = product_info[2]

    cursor.execute("SELECT * FROM customer_list WHERE id = %s", (customer_id,))
    customer_info = cursor.fetchone()

    cursor.execute("SELECT * FROM class_list WHERE id = %s", (class_id,))
    class_info = cursor.fetchone()

    # 获取客户列表
    cursor.execute('SELECT * FROM customer_list')
    customer_list = cursor.fetchall()
    customer_list = [customer_list for customer_list in customer_list if customer_list[0] != customer_id]

    # 获取分类列表
    cursor.execute('SELECT * FROM class_list')
    class_list = cursor.fetchall()
    class_list = [class_list for class_list in class_list if class_list[0] != class_id]

    cursor.close()
    conn.close()
    # 渲染编辑产品页面
    return render_template('product/product_info.html', product_info=product_info, customer_info=customer_info,
                           class_info=class_info, converted_path=converted_path, customer_list=customer_list,
                           class_list=class_list)


# 定义上传文件夹的绝对路径
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLDER = os.path.join(BASE_DIR, '../static/data/product_img')

# 检查文件夹是否存在，如果不存在，则创建
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}


def allowed_file(filename):
    return '.' in filename and \
        filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@list_product_bp.route('/upload_image_endpoint/<int:prod_id>', methods=['POST'])
def upload_image(prod_id):
    conn, cursor = create_db_connection()

    file = request.files['update-image']
    if file:
        if allowed_file(file.filename):
            timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
            _, file_extension = os.path.splitext(file.filename)
            filename = f"{timestamp}{file_extension}"
            file_path = os.path.join(UPLOAD_FOLDER, filename)

            # 压缩并保存图片
            compress_and_save_image(file, file_path)

            # 创建相对路径用于数据库保存
            relative_path = 'data/product_img/' + filename

            cursor.execute("SELECT image_path FROM product_list WHERE id = %s", (prod_id,))
            current_image_path = cursor.fetchone()[0]

            if current_image_path != 'img/Default_image.png':
                full_path = os.path.join(BASE_DIR, '../static', current_image_path)
                if os.path.exists(full_path):
                    os.remove(full_path)
                    print(f"文件 {full_path} 成功删除。")
                else:
                    print(f"文件 {full_path} 不存在。")

            cursor.execute("UPDATE product_list SET image_path = %s WHERE id = %s", (relative_path, prod_id))
            # 提交更改
            conn.commit()
            cursor.close()
            conn.close()

            flash('产品图片上传成功')
            return redirect('/product_info/{}'.format(prod_id))
        else:
            flash('产品图片为不支持的文件类型', 'error')
            return redirect('/product_info/{}'.format(prod_id))


# 更新产品信息
@list_product_bp.route('/product_save', methods=['POST'])
def product_save():
    conn, cursor = create_db_connection()
    try:
        # 从表单中获取产品信息
        prod_id = request.form['id']
        customer_id = request.form['customer_id']
        class_id = request.form['class_id']  # 应该是class_id而不是再次使用customer_id
        product_name = request.form['productName']
        product_model = request.form['productModel']
        product_color = request.form['productColor']
        product_unit = request.form['productUnit']
        purchase_price = request.form['purchasePrice']
        sales_price = request.form['salesPrice']

        form_data = {
            'customer_id': request.form['customer_id'].strip(),
            'class_id': request.form['class_id'].strip(),
            'product_name': request.form['productName'].strip(),
            'product_model': request.form['productModel'].strip(),
            'product_color': request.form['productColor'].strip(),
            'product_unit': request.form['productUnit'].strip(),
            'purchase_price': request.form['purchasePrice'].strip(),
            'sales_price': request.form['salesPrice'].strip(),
        }
        # 获取原始产品信息进行比较
        cursor.execute("SELECT * FROM product_list WHERE id = %s", (prod_id,))
        original_product = cursor.fetchone()
        original_data = {
            'customer_id': str(original_product[1]),
            'class_id': str(original_product[2]),
            'product_name': original_product[3],
            'product_model': original_product[4],
            'product_color': original_product[5],
            'product_unit': original_product[6],
            'purchase_price': str(original_product[7]),
            'sales_price': str(original_product[8]),
        }

        # 检查是否有编辑
        if all(form_data[key] == original_data[key] for key in form_data):
            flash('没有检测到任何更改。', 'info')
            return redirect('/product_info/{}'.format(prod_id))

        # 检查编辑后的产品信息是否与其他产品信息重复
        check_duplicate_query = '''
        SELECT id 
        FROM product_list 
        WHERE customer_id = %s AND product_name = %s AND product_model = %s AND id != %s
        '''
        cursor.execute(check_duplicate_query, (customer_id, product_name, product_model, prod_id))
        duplicate_record = cursor.fetchone()

        if duplicate_record:
            flash('存在一个相同的产品记录，请修改您的产品信息。', 'error')
            return redirect('/product_info/{}'.format(prod_id))

        if product_name is None or product_name.strip() == "":
            flash('产品名称不能为空!', 'error')
            return redirect('/product_info/{}'.format(prod_id))

        if product_unit is product_unit.strip() == "":
            product_unit = "PCS"

        def try_parse_float(value):
            """尝试将输入转换为浮点数，如果失败则抛出 ValueError"""
            try:
                return float(value)
            except ValueError as e:
                raise ValueError("请输入一个有效的数值。") from e

        # 处理采购价格
        try:
            if purchase_price is None:
                purchase_price = 0.0
            else:
                purchase_price = try_parse_float(purchase_price)
        except ValueError as error_message:
            flash(str(error_message), 'error')
            return redirect('/product_info/{}'.format(prod_id))

        # 处理销售价格
        try:
            if sales_price is None:
                sales_price = 0.0
            else:
                sales_price = try_parse_float(sales_price)
        except ValueError as error_message:
            flash(str(error_message), 'error')
            return redirect('/product_info/{}'.format(prod_id))

        # 更新数据库中的产品信息
        cursor.execute("UPDATE product_list SET customer_id = %s, class_id = %s, product_name = %s, product_model = %s, "
                       "product_color = %s, product_unit = %s, purchase_price = %s, sales_price = %s "
                       "WHERE id = %s",
                       (customer_id, class_id, product_name, product_model, product_color, product_unit,
                        purchase_price, sales_price, prod_id))
        conn.commit()

        # 重定向到产品列表页面或其他需要跳转的页面
        flash('产品信息更新成功')
        return redirect('/product_info/{}'.format(prod_id))
    finally:
        cursor.close()
        conn.close()